package com.diting.library.cmcc.util;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cmic.gen.sdk.auth.GenAuthnHelper;
import com.cmic.gen.sdk.auth.GenTokenListener;
import com.cmic.gen.sdk.view.AuthLoginCallBack;
import com.cmic.gen.sdk.view.GenAuthLoginListener;
import com.cmic.gen.sdk.view.GenAuthThemeConfig;
import com.cmic.gen.sdk.view.GenBackPressedListener;
import com.cmic.gen.sdk.view.GenCheckBoxListener;
import com.cmic.gen.sdk.view.GenCheckedChangeListener;
import com.cmic.gen.sdk.view.GenLoginClickListener;
import com.cmic.gen.sdk.view.GenLoginPageInListener;
import com.diting.library.cmcc.R;
import com.diting.library.cmcc.activity.ResultDialog;
import com.diting.library.cmcc.tokenValidate.Request;
import com.diting.library.cmcc.tokenValidate.RequestCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class CmicSSOHelper {
    private static String TAG = "MainActivity";

    public static final int RESULT = 0x111;
    public static final int RESULT_OF_SIM_INFO = 0x222;
    public static final int PERMISSIONS_REQUEST_READ_PHONE_STATE_PRE = 1000;
    public static final int PERMISSIONS_REQUEST_READ_PHONE_STATE_IMPLICIT_LOGIN = 2000;
    public static final int PERMISSIONS_REQUEST_READ_PHONE_STATE_DISPLAY_LOGIN = 3000;
    public static final int CMCC_SDK_REQUEST_GET_PHONE_INFO_CODE = 1111;
    public static final int CMCC_SDK_REQUEST_MOBILE_AUTH_CODE = 2222;
    public static final int CMCC_SDK_REQUEST_LOGIN_AUTH_CODE = 3333;
    public static final int CMCC_SDK_REQUEST_TOKEN_VALIDATE_CODE = 4444;
    public static final int CMCC_SDK_REQUEST_PHONE_VALIDATE_CODE = 5555;

    private GenAuthnHelper mGenAuthnHelper;
    private GenAuthThemeConfig.Builder themeConfigBuilder;
    private GenTokenListener mListener;
    private Context mContext;
    private String mAccessToken;
    boolean isShowResult = true;
    public String mResultString;
    public String mSDKVersion = null;
    private String[] operatorArray = {"未知", "移动", "联通", "电信"};
    private String[] networkArray = {"未知", "数据流量", "纯WiFi", "流量+WiFi"};
    Dialog alertDialog;

    public void initSDK(Context context, SSOResultListener ssoResultListener) {
        this.mContext = context;
        this.ssoResultListener = ssoResultListener;
        Log.e(TAG, System.currentTimeMillis() + " ");
        System.out.print(System.currentTimeMillis());
        GenAuthnHelper.setDebugMode(true);
        mGenAuthnHelper = GenAuthnHelper.getInstance(mContext.getApplicationContext());
        mGenAuthnHelper.setPageInListener(new GenLoginPageInListener() {
            @Override
            public void onLoginPageInComplete(String resultCode, JSONObject jsonObj) {
                if (resultCode.equals("200087")) {
                    Log.d("initSDK", "page in---------------");
                }
            }
        });
//        RelativeLayout relativeLayout = new RelativeLayout(this);
//        relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        themeConfigBuilder = new GenAuthThemeConfig.Builder()
                .setStatusBar(0xff0086d0, true)//状态栏颜色、字体颜色
//                .setAuthContentView(getLayoutInflater().inflate(R.layout.empty_layout,relativeLayout,false))
                .setAuthLayoutResID(R.layout.empty_layout)
                .setClauseStatusColor(Color.RED)
                .setClauseLayoutResID(R.layout.title_layout, "returnId")
                .setNavTextSize(20)
                .setNavTextColor(0xff0085d0)//导航栏字体颜色
                .setNavColor(Color.BLUE)
                .setNavHidden(true)

                .setNumberSize(20, true)////手机号码字体大小
                .setNumberColor(0xff333333)//手机号码字体颜色
                .setNumberOffsetX(30)//号码栏X偏移量
                .setNumFieldOffsetY_B(100)
                .setNumFieldOffsetY(100)//号码栏Y偏移量

//                .setLogBtnText("本机号码一键登录")//登录按钮文本
                .setLogBtnTextColor(0xffffffff)//登录按钮文本颜色
                .setLogBtnImgPath("umcsdk_login_btn_bg")//登录按钮背景
                .setLogBtnText(" ", 0xffffffff, 15, false)
                .setLogBtnOffsetY_B(200)//登录按钮Y偏移量
                .setLogBtnOffsetY(200)//登录按钮Y偏移量
//                .setLogBtn(500,30)
                .setLogBtnMargin(30, 30)
                .setCheckTipText("")
                .setGenBackPressedListener(new GenBackPressedListener() {
                    @Override
                    public void onBackPressed() {
                        Toast.makeText(mContext, "返回键回调", Toast.LENGTH_SHORT).show();
                    }
                })
                .setLogBtnClickListener(new GenLoginClickListener() {
                    @Override
                    public void onLoginClickStart(Context context, JSONObject jsonObj) {
                        alertDialog = new AlertDialog.Builder(context).create();
                        alertDialog.setCancelable(false);
                        alertDialog.setCanceledOnTouchOutside(false);
                        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                            @Override
                            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                                if (event.getAction() == KeyEvent.ACTION_UP) {
                                    dialog.dismiss();
                                    alertDialog = null;
                                }
                                return keyCode == KeyEvent.KEYCODE_BACK;
                            }
                        });
                        alertDialog.show();
                        alertDialog.setContentView(LayoutInflater.from(mContext).inflate(R.layout.loading_alert, null));
                    }

                    @Override
                    public void onLoginClickComplete(Context context, JSONObject jsonObj) {
                        if (alertDialog != null && alertDialog.isShowing()) {
                            alertDialog.dismiss();
                            alertDialog = null;
                        }
                    }
                })

                .setGenCheckBoxListener(new GenCheckBoxListener() {
                    @Override
                    public void onLoginClick(Context context, JSONObject jsonObj) {
                        Toast.makeText(context, "自定义勾选提示", Toast.LENGTH_LONG).show();
                    }
                })

                .setGenAuthLoginListener(new GenAuthLoginListener() {
                    @Override
                    public void onAuthLoginListener(Context context, AuthLoginCallBack authLoginCallBack) {
                        showPrivacyAlertDialog(context, authLoginCallBack);
                    }
                })

                .setGenCheckedChangeListener(new GenCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(boolean b) {
                        Log.d("是否勾选协议", b + "");
                    }
                })

                .setCheckedImgPath("umcsdk_check_image")//checkbox被勾选图片
                .setUncheckedImgPath("umcsdk_uncheck_image")//checkbox未被勾选图片
                .setCheckBoxImgPath("umcsdk_check_image", "umcsdk_uncheck_image", 9, 9)
                .setPrivacyState(false)//授权页check

                .setPrivacyAlignment("登录即同意" + GenAuthThemeConfig.PLACEHOLDER + "应用自定义服务条款一、应用自定义服务条款二、条款3和条款4并使用本机号码校验", "应用自定义服务条款一", "https://www.baidu.com", "应用自定义服务条款二", "https://www.hao123.com",
                        "条款3", "http://www.sina.com", "条款4", "http://gz.58.com")
                .setPrivacyText(10, 0xff666666, 0xff0085d0, false, true)
                .setClauseColor(0xff666666, 0xff0085d0)//条款颜色

                .setPrivacyMargin(20, 30)
                .setPrivacyOffsetY(30)//隐私条款Y偏移量
                .setPrivacyOffsetY_B(50)//隐私条款Y偏移量
                .setCheckBoxLocation(1)
                .setAppLanguageType(0)
                .setBackButton(true)
                .setWebDomStorage(true)
                .setPrivacyAnimation("umcsdk_anim_shake")
                .setPrivacyBookSymbol(true)

//                .setAuthPageActIn("in_activity","out_activity")
//                .setAuthPageActOut("in_activity","out_activity")

//                .setAuthPageWindowMode(300, 300)
//                .setAuthPageWindowOffset(0,0)
                .setThemeId(R.style.loginDialog);
//                .setWindowBottom(1)

        mGenAuthnHelper.setAuthThemeConfig(themeConfigBuilder.build());
        Log.e(TAG, System.currentTimeMillis() + " ");
        mSDKVersion = GenAuthnHelper.SDK_VERSION;

        mListener = new GenTokenListener() {
            @Override
            public void onGetTokenComplete(int SDKRequestCode, JSONObject jObj) {
                if (jObj != null) {
                    try {
                        if (isShowResult) {
                            //时间
//                            long phoneTimes = SpUtils.getLong("phoneTimes");
                            long phoneTimes = System.currentTimeMillis();
                            jObj.put("phoneTimes", System.currentTimeMillis() - phoneTimes + "ms");
                            mResultString = jObj.toString();
                        }
                        if (jObj.has("token")) {
                            mAccessToken = jObj.optString("token");
                            HashMap<String, String> map = new HashMap<>(2);
                            map.put("token", mAccessToken);
                            mGenAuthnHelper.quitAuthActivity();
                            if (ssoResultListener != null) {
                                ssoResultListener.onResult(mResultString, 200);
                            }
//                            mHandler.sendEmptyMessageDelayed(RESULT, 200);
                            isShowResult = false;
                        } else {
//                            mHandler.sendEmptyMessage(RESULT);
                            if (ssoResultListener != null) {
                                ssoResultListener.onResult(mResultString, 0);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    private SSOResultListener ssoResultListener;

    public interface SSOResultListener {
        void onResult(String result, int delay);

        void onSimInfo(String info);
    }

    private AlertDialog privacyAlertDialog;

    public void showPrivacyAlertDialog(Context context, AuthLoginCallBack authLoginCallBack) {

        Point size = MobileParmUtil.getRealSize(mContext);
        boolean isPortrait = size.x < size.y;
        int dp15 = MobileParmUtil.dip2px(mContext, 15);
        int dp23 = MobileParmUtil.dip2px(mContext, 23);
        int dp20 = MobileParmUtil.dip2px(mContext, 20);
        int dp30 = MobileParmUtil.dip2px(mContext, 30);
        int dp38 = MobileParmUtil.dip2px(mContext, 38);
        privacyAlertDialog = new AlertDialog.Builder(context).create();
        privacyAlertDialog.setCancelable(false);
        privacyAlertDialog.setCanceledOnTouchOutside(false);
        privacyAlertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return keyCode == KeyEvent.KEYCODE_BACK;
            }
        });
        LinearLayout layout = new LinearLayout(privacyAlertDialog.getContext());
        float[] bgRadius = {23f, 23f, 23f, 23f, 23f, 23f, 23f, 23f};
        float[] btnRadius = {0f, 0f, 0f, 0f, 0f, 0f, 23f, 23f};
        float[] btnRadius2 = {0f, 0f, 0f, 0f, 23f, 23f, 0f, 0f};
        layout.setBackground(MobileParmUtil.createRectangleDrawable(Color.WHITE, Color.WHITE, 0, bgRadius));
        layout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams bgLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        bgLp.setMargins(dp100,0,dp100,0);
        layout.setLayoutParams(bgLp);

        TextView privacy = new TextView(privacyAlertDialog.getContext());
        privacy.setGravity(Gravity.CENTER_HORIZONTAL);
        privacy.setTextSize(15);
        privacy.setIncludeFontPadding(false);
        privacy.setTextColor(Color.BLUE);
        LinearLayout.LayoutParams privacyLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        int marginLeft = isPortrait ? dp15 : dp23;
        privacyLp.setMargins(marginLeft, dp38, marginLeft, dp30);
        privacy.setText("同意授权？");
        privacy.setMovementMethod(LinkMovementMethod.getInstance());
        privacy.setHighlightColor(mContext.getResources().getColor(android.R.color.transparent));
        layout.addView(privacy, privacyLp);

        LinearLayout buttonLayout = new LinearLayout(privacyAlertDialog.getContext());
        LinearLayout.LayoutParams btnLayoutLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        buttonLayout.setLayoutParams(btnLayoutLp);
        buttonLayout.setOrientation(LinearLayout.HORIZONTAL);

        LinearLayout.LayoutParams btnLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
        Button cancelBtn = new Button(privacyAlertDialog.getContext());
        cancelBtn.setText("取消");
        cancelBtn.setPadding(0, dp15, 0, dp15);
        cancelBtn.setTextColor(0xFF3486D9);
        cancelBtn.setTextSize(16);
        cancelBtn.setBackground(MobileParmUtil.createRectangleDrawable(Color.WHITE, 0xFFA6A6A6, 1, btnRadius));
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                privacyAlertDialog.dismiss();
            }
        });
        Button authBtn = new Button(privacyAlertDialog.getContext());
        authBtn.setText("同意并继续");
        authBtn.setPadding(0, dp15, 0, dp15);
        authBtn.setTextColor(0xFF3486D9);
        authBtn.setTextSize(16);
        authBtn.setBackground(MobileParmUtil.createRectangleDrawable(Color.WHITE, 0xFFA6A6A6, 1, btnRadius2));
        authBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                authLoginCallBack.onAuthLoginCallBack(true);
                privacyAlertDialog.dismiss();
            }
        });
        buttonLayout.addView(cancelBtn, btnLp);
        buttonLayout.addView(authBtn, btnLp);

        layout.addView(buttonLayout);


        privacyAlertDialog.show();
        privacyAlertDialog.setContentView(layout);
        Window window = privacyAlertDialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.CENTER;
            lp.width = (int) (size.x * 0.75);//宽高设置具体大小
            privacyAlertDialog.getWindow().setAttributes(lp);
        }
    }

    /**
     * 需要权限：READ_PHONE_STATE， ACCESS_NETWORK_STATE
     * operatorType获取网络运营商: 0.未知 1.移动流量 2.联通流量网络 3.电信流量网络
     * networkType 网络状态：0未知；1流量 2 wifi；3 数据流量+wifi
     */
    public void getNetAndOperator() {
        JSONObject jsonObject = mGenAuthnHelper.getNetworkType(mContext);
        int operator, net;
        try {
            operator = Integer.parseInt(jsonObject.getString("operatortype"));
            net = Integer.parseInt(jsonObject.getString("networktype"));
            jsonObject.put("operatorType", operatorArray[operator]);
            jsonObject.put("networkType", networkArray[net]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mResultString = jsonObject.toString();
        if (ssoResultListener != null) {
            ssoResultListener.onResult(mResultString, 0);
        }
//        mResultDialog.setResult(StringFormat.logcatFormat(mResultString));
    }


    /**
     * 授权登录处理
     */
    private void displayLogin(Activity activity) {
//        SpUtils.putLong("getPrePhoneTimes", 0);
//        SpUtils.putLong("phoneTimes", System.currentTimeMillis());
        if (Build.VERSION.SDK_INT >= 23) {
            if (mContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
                        PERMISSIONS_REQUEST_READ_PHONE_STATE_DISPLAY_LOGIN);
            } else {
                mGenAuthnHelper.loginAuth(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_LOGIN_AUTH_CODE);
            }
        } else {
            mGenAuthnHelper.loginAuth(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_LOGIN_AUTH_CODE);
        }
    }

    /**
     * 弹窗授权登录
     */
    public void tryAuthLoginByDialog(Activity activity) {
        themeConfigBuilder.setAuthPageWindowMode(300, 300)
                .setNumFieldOffsetY(50)
                .setLogBtnOffsetY(120)
//                        .setWindowBottom(1)
//                        .setAuthPageWindowOffset(0,0)
                .setThemeId(R.style.loginDialog);
        mGenAuthnHelper.setAuthThemeConfig(themeConfigBuilder.build());
        displayLogin(activity);
    }

    /**
     * 授权登录
     */
    public void tryAuthLogin(Activity activity) {
        themeConfigBuilder.setAuthPageWindowMode(0, 0)
                .setThemeId(-1);
        mGenAuthnHelper.setAuthThemeConfig(themeConfigBuilder.build());
        displayLogin(activity);
    }


    /**
     * 本机号码校验
     */
    public void phoneValidate(String phone) {
        phoneValidate(phone, Constant.APP_ID, Constant.APP_KEY, mAccessToken, mListener);
    }

    public void phoneValidate(String phone, final String appId, final String appKey, final String token, final GenTokenListener listener) {
        Bundle values = new Bundle();
        values.putString("appKey", appKey);
        values.putString("appId", appId);
        values.putString("token", token);
        values.putString("phone", phone);
//        SpUtils.putLong("phoneTimes", System.currentTimeMillis());
        Request.getInstance(mContext).phoneValidate(values, new RequestCallback() {
            @Override
            public void onRequestComplete(String resultCode, String resultDes, JSONObject jsonObj) {
                Log.i("Token校验结果：", jsonObj.toString());
                listener.onGetTokenComplete(CMCC_SDK_REQUEST_PHONE_VALIDATE_CODE, jsonObj);
            }
        });
    }


    /**
     * getPhoneInfo(取号)
     */
    public void PGWGetMobile(Activity activity) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (mContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
                        PERMISSIONS_REQUEST_READ_PHONE_STATE_PRE);
            } else {
//                SpUtils.putLong("phoneTimes", System.currentTimeMillis());
                mGenAuthnHelper.getPhoneInfo(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_GET_PHONE_INFO_CODE);
            }
        } else {
//            SpUtils.putLong("phoneTimes", System.currentTimeMillis());
            mGenAuthnHelper.getPhoneInfo(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_GET_PHONE_INFO_CODE);
        }
    }

    public void getMobile() {
        mGenAuthnHelper.getPhoneInfo(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_GET_PHONE_INFO_CODE);
    }

    public void mobileAuth() {
        mGenAuthnHelper.mobileAuth(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_MOBILE_AUTH_CODE);
    }

    public void logAuth() {
        mGenAuthnHelper.loginAuth(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_LOGIN_AUTH_CODE);
    }

    /**
     * mobileAuth(号码校验)
     */
    public void implicitLogin(Activity activity) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (mContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
                        PERMISSIONS_REQUEST_READ_PHONE_STATE_IMPLICIT_LOGIN);
            } else {
//                SpUtils.putLong("phoneTimes", System.currentTimeMillis());
                mGenAuthnHelper.mobileAuth(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_MOBILE_AUTH_CODE);
            }
        } else {
//            SpUtils.putLong("phoneTimes", System.currentTimeMillis());
            mGenAuthnHelper.mobileAuth(Constant.APP_ID, Constant.APP_KEY, mListener, CMCC_SDK_REQUEST_MOBILE_AUTH_CODE);
        }
    }

    public void testUserInfo() {
        getUserInfo(Constant.APP_ID, Constant.APP_SECRET);
    }

    /**
     * 获取用户信息
     */
    public void getUserInfo(String appid, String appSecret) {
        tokenValidate(appid, appSecret, mAccessToken, mListener);
    }

    /**
     * 获取用户信息
     */
    public void tokenValidate(final String appId, final String appKey, final String token, final GenTokenListener listener) {
        Bundle values = new Bundle();
        values.putString("appSecret", appKey);
        values.putString("appId", appId);
        values.putString("token", token);
//        SpUtils.putLong("phoneTimes", System.currentTimeMillis());
        Request.getInstance(mContext).tokenValidate(values, new RequestCallback() {
            @Override
            public void onRequestComplete(String resultCode, String resultDes, JSONObject jsonObj) {
                Log.i("Token校验结果：", jsonObj.toString());
                listener.onGetTokenComplete(CMCC_SDK_REQUEST_TOKEN_VALIDATE_CODE, jsonObj);
                String phone = jsonObj.optString("msisdn");
                HashMap<String, String> map = new HashMap<>(2);
                map.put("token", mAccessToken);
                map.put("msisdn", phone);
            }
        });
    }


    /**
     * 配置超时时间
     */
    public void authOverTime(Integer overTime) {
        if (overTime != null && overTime > 0) {
            mGenAuthnHelper.setOverTime(overTime);
        } else {
            mGenAuthnHelper.setOverTime(8000);
        }
    }

    public void deleteScrip() {
        mGenAuthnHelper.delScrip();
        Toast.makeText(mContext, "清除scrip成功", Toast.LENGTH_LONG).show();
    }

    public void onDestroy() {
        mGenAuthnHelper.deleteAuthThemeConfig();
        mGenAuthnHelper.setPageInListener(null);
        mListener = null;
    }

}
